/**
 * 
 */
package com.verisette.ncos.web.card.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.corp.agi.service.bean.ServiceRequest;
import org.corp.agi.service.bean.ServiceResponse;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.web.action.BaseAction;
import org.corp.agi.web.constant.WebConstant;
import org.corp.agi.web.util.ServiceRequestFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;

import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterMember;
import com.verisette.ncos.persistence.domain.TransCustomerOrder;
import com.verisette.ncos.service.approver.gateway.ApproverService;
import com.verisette.ncos.service.card.gateway.CardService;

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TextDispatchAction extends BaseAction {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(TextDispatchAction.class);
	
	private InputStream inputStream;
	private String contentType;
	private String contentDisposition;
	
	private Integer orderId;
	
	private String name;
	private String isTemp;
	private String isDownload;
	private String isPrint;
	private String isPO;
	
	private String isComma = "Y";
	
	private String DELIM_TAB = "\t";
	private String DELIM_COMMA = ",";
	
	private String DELIMITER = "=";
	private String NEWLINE = "\r\n";
	

	private CardService cardService;
	@Autowired
	@Required
	public void setCardService(CardService cardService) {
		this.cardService = cardService;
	}
	
//	private final String[] HEADER_LIST = {"\"FNAME_TH\"", "\"LNAME_TH\"", "\"POSITION_TH\"", "\"AGENT_CODE\"", "\"EMAIL\"", "\"EMAIL2\"", "\"COMPANY_NAME_TH\"",
//			"\"OFFICE_NAME_TH\"", "\"OFFICE_ADDRESS_TH\"", "\"OFFICE_ADDRESS2_TH\"", "\"PHONE\"", "\"PHONE2\"", "\"FAX\"", "\"FAX2\"", "\"MOBILE\"", "\"MOBILE2\"",
//			"\"FNAME_EN\"", "\"LNAME_EN\"", "\"POSITION_EN\"", "\"AGENT_CODE\"", "\"EMAIL\"", "\"EMAIL2\"", "\"COMPANY_NAME_EN\"",
//			"\"OFFICE_NAME_EN\"", "\"OFFICE_ADDRESS_EN\"", "\"OFFICE_ADDRESS2_EN\"", "\"PHONE\"", "\"PHONE2\"", "\"FAX\"", "\"FAX2\"", "\"MOBILE\"", "\"MOBILE2\""
//	};

	private final String[] HEADER_LIST = {"FNAME_TH", "LNAME_TH", "POSITION_TH", "AGENT_CODE", "EMAIL", "EMAIL2", "COMPANY_NAME_TH",
			"OFFICE_NAME_TH", "OFFICE_ADDRESS_TH", "OFFICE_ADDRESS2_TH", "PHONE", "PHONE2", "FAX", "FAX2", "MOBILE", "MOBILE2",
			"FNAME_EN", "LNAME_EN", "POSITION_EN", "AGENT_CODE", "EMAIL", "EMAIL2", "COMPANY_NAME_EN",
			"OFFICE_NAME_EN", "OFFICE_ADDRESS_EN", "OFFICE_ADDRESS2_EN", "PHONE", "PHONE2", "FAX", "FAX2", "MOBILE", "MOBILE2"
	};
	
	public String execute(){
		
    	String fileName = null;
    	try {
    		
    		if("Y".equals(isComma)){
    			DELIMITER = DELIM_COMMA;
    		} else {
    			DELIMITER = DELIM_TAB;
    		}
    		
    		String userName = ((UserBean)httpServletRequest.getSession().getAttribute(WebConstant.SESSION_USERBEAN_KEY)).getUsername();
    		
			contentType="plain/text";
			
			TransCustomerOrder order = new TransCustomerOrder();
			order.setOrderId(orderId);
			

			ServiceRequest req = ServiceRequestFactory.getNewServiceRequest(httpServletRequest);
			req.setValueObject(order);
			
			ServiceResponse<TransCustomerOrder> res = cardService.inquiryCardOrderById(req);
			if(isServiceResponseSuccess(res))
			{
				order = res.getValueObject();
				name = order.getOrderNoDisp();
			}
			
			MasterMember member = order.getMasterMember();
			StringBuilder headerBD = new StringBuilder();
			for(String header : HEADER_LIST) { 
				headerBD.append(header);
				headerBD.append(DELIMITER);
			}
			headerBD.deleteCharAt(headerBD.length()-1);

//			private final String[] HEADER_LIST = {"FNAME_TH", "LNAME_TH", "POSITION_TH", "AGENT_CODE", "EMAIL", "EMAIL2", "COMPANY_NAME_TH",
//					"OFFICE_NAME_TH", "OFFICE_ADDRESS_TH", "OFFICE_ADDRESS2_TH", "PHONE", "PHONE2", "FAX", "FAX2", "MOBILE", "MOBILE2",
//					"FNAME_EN", "LNAME_EN", "POSITION_EN", "AGENT_CODE", "EMAIL", "EMAIL2", "COMPANY_NAME_EN",
//					"OFFICE_NAME_EN", "OFFICE_ADDRESS_EN", "OFFICE_ADDRESS2_EN", "PHONE", "PHONE2", "FAX", "FAX2", "MOBILE", "MOBILE2"
//			};
			
			StringBuilder sbd = new StringBuilder(headerBD);
			sbd.append(NEWLINE);
			sbd.append(trimToEmpty(member.getMmbFnameTh()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbLnameTh()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPositionTh()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbAgentCode()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbEmail()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbEmail2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbCompanyNameTh()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbOfficeNameTh()));
			sbd.append(DELIMITER);
			sbd.append(member.getMmbOfficeAddrTh());
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbOfficeAddr2Th()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPhone()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPhone2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbFax()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbFax2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbMobile()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbMobile2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbFnameEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbLnameEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPositionEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbAgentCode()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbEmail()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbEmail2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbCompanyNameEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbOfficeNameEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbOfficeAddrEn()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbOfficeAddr2En()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPhone()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbPhone2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbFax()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbFax2()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbMobile()));
			sbd.append(DELIMITER);
			sbd.append(trimToEmpty(member.getMmbMobile2()));
			
			inputStream = new ByteArrayInputStream(sbd.toString().getBytes(ProjectConstant.EXPORT_ENCODE_TIS620));
			// set extension
			if(name!=null && !name.endsWith(".txt")){
				name += ".txt";
			}
			fileName = name;
			
			// set File-name to PDF Files TIS-620
//			fileName = URLEncoder.encode(fileName,ProjectConstant.EXPORT_ENCODE_TIS620);
			
			contentDisposition="filename="+fileName+";"; 
			if("Y".equals(isDownload)){
				contentDisposition = "attachment;" + contentDisposition;
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
//			try {
//				String path = ProjectConstant.BASE_APP_FOLDER + "\\RESOURCES\\PDF\\";
//				File theFile = new File(path+"DefaultNameCard.pdf");
//				contentType="application/pdf";
//			
//				inputStream = new FileInputStream(theFile);
//			
//				// set extension
//				fileName = theFile.getName();
//				
//				// set File-name to UTF-8
//				fileName = URLEncoder.encode(fileName, "UTF-8");
//				
//				contentDisposition="filename="+fileName+";";
//			} catch (UnsupportedEncodingException e1) {
//				// TODO Auto-generated catch block
//				logger.error(e1.getMessage(), e1);
//			} catch (FileNotFoundException e2) {
//				// TODO Auto-generated catch block
//				logger.error(e2.getMessage(), e2);
//			}
		}
    	return SUCCESS;
    }
	
	private String trimToEmpty(String s){
		if(s==null){
			s="";
		}
		return s.trim();
//		return "\""+s.trim() +"\"";
	}

	public String getIsPO() {
		return isPO;
	}

	public void setIsPO(String isPO) {
		this.isPO = isPO;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getIsTemp() {
		return isTemp;
	}

	public void setIsTemp(String isTemp) {
		this.isTemp = isTemp;
	}

	public String getIsDownload() {
		return isDownload;
	}

	public void setIsDownload(String isDownload) {
		this.isDownload = isDownload;
	}

	public String getIsPrint() {
		return isPrint;
	}

	public void setIsPrint(String isPrint) {
		this.isPrint = isPrint;
	}

	public Integer getOrderId() {
		return orderId;
	}

	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}

	public String getIsComma() {
		return isComma;
	}

	public void setIsComma(String isComma) {
		this.isComma = isComma;
	}
}
